package org.newcih.dao;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * 单例模式：创建sessionFactory的单例
 *
 * @author Administrator
 */
public class HibernateUtil {
    //1.私有的常量：声明的同时就必须要初始化
    private static final SessionFactory sessionFactory = buildSessionFactory();

    //2.私有的创建方法
    private static SessionFactory buildSessionFactory() {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
        try {
            return new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } catch (Exception e) {
            StandardServiceRegistryBuilder.destroy(registry);
            e.printStackTrace();
        }
        return null;
    }

    //3.提供公共的外部访问（已经初始化后的）单例方法
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void main(String[] args) {
        System.out.println(HibernateUtil.getSessionFactory());
    }
}
